<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ConsumptionBillApi } from '#/api/spa/consumption';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { message, Tabs } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteConsumptionBill,
  exportConsumptionBill,
  getConsumptionBillPage,
} from '#/api/spa/consumption';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import ConsumptionDetailList from './modules/consumption-detail-list.vue';
import Form from './modules/form.vue';

/** 子表的列表 */
const subTabsName = ref('consumptionDetail');
const selectConsumptionBill = ref<ConsumptionBillApi.ConsumptionBill>();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建SPA消费账单 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑SPA消费账单 */
function handleEdit(row: ConsumptionBillApi.ConsumptionBill) {
  formModalApi.setData(row).open();
}

/** 删除SPA消费账单 */
async function handleDelete(row: ConsumptionBillApi.ConsumptionBill) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    key: 'action_key_msg',
  });
  try {
    await deleteConsumptionBill(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 导出表格 */
async function handleExport() {
  const data = await exportConsumptionBill(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: 'SPA消费账单.xls', source: data });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: '600px',
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getConsumptionBillPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
      isCurrent: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<ConsumptionBillApi.ConsumptionBill>,
  gridEvents: {
    cellClick: ({ row }: { row: ConsumptionBillApi.ConsumptionBill }) => {
      selectConsumptionBill.value = row;
    },
  },
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />

    <div>
      <Grid table-title="消费账单列表">
        <template #toolbar-tools>
          <TableAction
            :actions="[
              {
                label: $t('ui.actionTitle.create', ['消费账单']),
                type: 'primary',
                icon: ACTION_ICON.ADD,
                auth: ['spa:consumption-bill:create'],
                onClick: handleCreate,
              },
              {
                label: $t('ui.actionTitle.export'),
                type: 'primary',
                icon: ACTION_ICON.DOWNLOAD,
                auth: ['spa:consumption-bill:export'],
                onClick: handleExport,
              },
            ]"
          />
        </template>
        <template #actions="{ row }">
          <TableAction
            :actions="[
              {
                label: $t('common.edit'),
                type: 'link',
                icon: ACTION_ICON.EDIT,
                auth: ['spa:consumption-bill:update'],
                onClick: handleEdit.bind(null, row),
              },
              {
                label: $t('common.delete'),
                type: 'link',
                danger: true,
                icon: ACTION_ICON.DELETE,
                auth: ['spa:consumption-bill:delete'],
                popConfirm: {
                  title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                  confirm: handleDelete.bind(null, row),
                },
              },
            ]"
          />
        </template>
      </Grid>

      <!-- 子表的表单 -->
      <Tabs v-model:active-key="subTabsName" class="mt-2">
        <Tabs.TabPane key="consumptionDetail" tab="消费明细" force-render>
          <ConsumptionDetailList :bill-id="selectConsumptionBill?.id" />
        </Tabs.TabPane>
      </Tabs>
    </div>
  </Page>
</template>
